import React, { useContext, useEffect, useState } from "react";
import classNames from "classnames";
import type { QuickFilterProps } from "./type";
import { ThemeContext } from "../theme";
import Item from "./components/Item";
import MoreButton from "./components/MoreButton";
import { createUseStyles } from "react-jss";
import { isDef, isUndefined } from "@ct0/functions";
import {
  useQuickFilterFn,
  useQuickFilterWithPageFn,
  writeQuickFilterToUrlFn,
} from "./hook";

const useStyles = createUseStyles({
  quickFilter: {
    display: "flex",
    flexWrap: "wrap",
    gap: "16px",
  },
  fontSize: {
    fontSize: (props: { fontSize: number }) => props.fontSize,
  },
  input: {
    width: "150px",
    padding: "3px 5px",
    borderRadius: "4px",
    border: "1px solid #D9D9D9",
    color: "#333",
    overflow: "hidden",
    display: "flex",
    "&:focus-visible": {
      outline: 0,
    },
  },
});

export default QuickFilter;

QuickFilter.useQuickFilterWithPage = useQuickFilterWithPageFn;
QuickFilter.useQuickFilter = useQuickFilterFn;
QuickFilter.writeQuickFilterToUrl = writeQuickFilterToUrlFn;

function QuickFilter<VALUE extends Record<string, any>>({
  value: propsValue,
  items,
  shadow = true,
  moreButton = true,
  onChange,
  tailSlot,
  itemSelection,
  emptyLabel,
  getItemPopupContainer,
}: QuickFilterProps<VALUE>) {
  const [showKeys, setShowKeys] = useState(() => {
    //FIXME: 兼容旧的配置项 如果存在itemSelection?.selectedItemKeys，则不采用items中defaultVisible不为false
    if (itemSelection?.selectedItemKeys) return itemSelection.selectedItemKeys;
    const keys = [];
    for (const i of items) {
      if (i.defaultVisible === false) continue;
      keys.push(i.key);
    }
    return keys;
  });

  useEffect(() => {
    if (propsValue) {
      //FIXME: 兼容旧的配置项 如果存在itemSelection?.selectedItemKeys，则不采用value中的key
      if (itemSelection?.selectedItemKeys) {
        return;
      }
      const newKeys: Array<string> = [];
      for (const [k, v] of Object.entries(propsValue)) {
        if (isDef(v) && !showKeys.includes(k)) newKeys.push(k);
      }
      if (newKeys.length) setShowKeys(showKeys.concat(newKeys));
    }
  }, [propsValue]);

  useEffect(() => {
    // 检查 QuickFilter 配置是否有问题
    const keys: Array<string> = [];
    for (const i of items) {
      if (keys.includes(i.key))
        throw Error(`QuickFilter 的 items 配置项不能有重复的 key: ${i.key}`);
      else keys.push(i.key);
    }
  }, []);

  const { fontSize } = useContext(ThemeContext);
  const classes = useStyles({ fontSize });

  const handler = (key: string, v: any) => {
    const newValue = { ...propsValue };
    (newValue as any)[key] = v;
    onChange?.(newValue as VALUE);
  };

  const moreButtonOptions = items.map((i) => ({
    label: i.label,
    value: i.key,
  }));

  const handleSelectChange = (keys: string[]) => {
    const selectItems = items.filter((x) => keys.includes(x.key));
    if (isUndefined(itemSelection)) {
      setShowKeys(keys);
    }
    itemSelection?.onChange?.(keys, selectItems);
  };

  useEffect(() => {
    if (itemSelection?.selectedItemKeys) {
      setShowKeys(itemSelection?.selectedItemKeys);
    }
  }, [itemSelection?.selectedItemKeys]);

  return (
    <div className={classNames(classes.quickFilter, classes.fontSize)}>
      {items.map((i) => {
        if (!showKeys.includes(i.key)) return;
        return (
          <Item
            shadow={shadow}
            key={i.key}
            value={propsValue?.[i.key]}
            field={i}
            onChange={handler}
            emptyLabel={emptyLabel}
            getPopupContainer={getItemPopupContainer}
          />
        );
      })}
      {moreButton && (
        <MoreButton
          value={showKeys}
          shadow={shadow}
          options={moreButtonOptions}
          onChange={handleSelectChange}
        />
      )}
      {tailSlot}
    </div>
  );
}
